import { register, login,getUser,getQuote } from '../service/users';
import router from 'umi/router'
import { message } from 'antd'
import cookie from 'react-cookies'
import {userId} from '@/constant'

const creator=(type,payload)=>({type,payload})
export default {
  namespace: 'users',
  state: { 
    users:[],
    quotes:{},
   },
  reducers: {
    saveId(state, { payload}) {
      return {
        ...state,
        id:payload
      }
    },
    saveUser(state,{payload}){
      return {
        ...state,
        users:payload
      }
    },
    saveQuote(state,{payload}){
      return {
        ...state,
        quotes:payload
      }
    }
  },
  effects: {
    *register({ payload }, { call, put }) {
      const {code}=payload
      let res = yield call(register, payload)
      if (res.httpStatus === 200) {
        if(code!=='0'){//code等于0表示获取验证码
          router.push('/users/login')
        }
        
      } else {
        message.warn(`${res.msg}`)
      }
      return res
    },
    //登入
    *login({payload}, { call, put }) {
      
      let res = yield call(login, payload);
      if (res.httpStatus === 200) {
        const {id}=res;
        window.sessionStorage.setItem(userId,id)
        // yield put(creator('saveId',id))
        router.push('/my-world/plan')

      } else {
        message.warn(`${res.msg}`)
      }
      return res;
    },
    *getUser({payload},{call,put}){
      let res=yield call(getUser,payload)
      if(res.httpStatus===200){
        yield put(creator('saveUser',res.data))
      }
    },
    *getQuote({payload},{call,put}){
      let res=yield call(getQuote,payload)
      if(res.httpStatus===200){
        yield put(creator('saveQuote',res.data[0]))
      }
    }
  },
  //监听路由
  // subscriptions: {
  //   setup({ dispatch, history }) {
  //     return history.listen(({ pathname, query }) => {
  //       if (pathname === '/users') {
  //         console.log(query,9999)
  //         dispatch({ type: 'fetch', payload: query });
  //       }
  //     })
  //   }
  // }
}

